from application.enumeration.StatusCodeEnum import StatusCodeEnum
from application.util.StringUtil import md5_encode, is_valid_url
from application.exception.BasicException import BasicException
from application.mapper.VideoMapper import VideoMapper
from application.model.VideoModel import VideoModel


async def add_video(video_url: str) -> str:
    """
    新增视频
    :param video_url: 视频URL
    :return: 视频MD5索引
    """
    if not is_valid_url(video_url):
        raise BasicException(status_code=StatusCodeEnum.BAD_REQUEST_ERROR.value, message="视频URL不合法！")
    md5_index: str = md5_encode(video_url)  # md5索引
    # 如果数据库中已存在该视频，则直接返回
    if not await VideoMapper.get_data_by_field(md5=md5_index):
        # 新增视频
        video_model: VideoModel = VideoModel(
            url=video_url,
            md5=md5_encode(video_url)
        )
        if not await VideoMapper.insert(data=video_model.to_dict()):
            raise BasicException(status_code=StatusCodeEnum.ERROR.value, message="新增视频失败！")
    return md5_index


async def batch_add_video(video_list: list) -> list:
    """
    批量新增视频
    :param video_list: 视频URL列表
    :return: 视频MD5索引列表
    """
    result: list = []
    video_model_list: list = []
    for video_url in video_list:
        if not is_valid_url(video_url):
            raise BasicException(status_code=StatusCodeEnum.BAD_REQUEST_ERROR.value, message="视频URL不合法！")
        md5_index: str = md5_encode(video_url)  # md5索引
        # 如果数据库中已存在该视频，则跳过
        if await VideoMapper.get_data_by_field(md5=md5_index):
            continue
        video_model_list.append(VideoModel(url=video_url, md5=md5_encode(video_url)))
        result.append(md5_index)  # 添加md5索引到返回结果中
    # 批量新增
    if not await VideoMapper.batch_insert(model_list=video_model_list):
        raise BasicException(status_code=StatusCodeEnum.ERROR.value, message="批量新增视频失败！")
    return result
